﻿//===================================================================================
// Copyright (c) Ryan Garrett.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
using System;
using System.ComponentModel;

namespace Caffeine.Core.ModelProperty
{
    internal sealed class NullableValueTypeProperty<T> : ModelProperty<Nullable<T>> where T : struct, IEquatable<T>
    {
        public NullableValueTypeProperty(ModelBase parent, String name, Nullable<ModelPropertyBehaviors> behavior, Boolean isWrapped)
            : base(parent, name, behavior, isWrapped)
        {
        }

        public override Boolean IsNullable
        {
            get
            {
                return true;
            }
        }

        public override String ToString()
        {
            String stringValue = null;

            if (Value != null)
            {
                stringValue = Value.ToString();
            }

            return stringValue;
        }

        internal override void MergeAdjacentProperty(ModelPropertyBase property)
        {
            Value = (property as NullableValueTypeProperty<T>).Value;
        }

        protected override Boolean OnCompareValues(Nullable<T> currentValue, Nullable<T> newValue)
        {
            Boolean areEqual = false;

            if (currentValue.HasValue && newValue.HasValue)
            {
                areEqual = currentValue.Value.Equals(newValue.Value);
            }
            else
            {
                areEqual = !currentValue.HasValue && !newValue.HasValue;
            }

            return areEqual;
        }
    }
}
